package com.rightsidetech.http.aspect;

import com.alibaba.fastjson.JSON;
import com.rightsidetech.commom.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;


    @Before("execution(* com.rightsidetech.*.controller..*.*(..)) " +
            "&& @annotation(com.rightsidetech.http.aspect.Log)")
    public void doAround(JoinPoint pjp) throws Exception {
        checkToken(pjp);
    }

    private void checkToken(JoinPoint pjp) throws Exception {

        //打印请求日志(临时)
        try {
            log.info("----------请求开始----------");
            log.info("url={}", request.getRequestURL());
            log.info("method={}", request.getMethod());
            if(!StringUtil.isNullorEmpty(request.getHeaders("ip")) && request.getHeaders("ip").hasMoreElements()){
                String ip2 = request.getHeaders("ip").nextElement().replace("/","");
                String ip = ip2.split(":")[0];
                log.info("ip={}",ip);
                request.setAttribute("ip",ip);
            }else{
                log.info("ip={}", request.getRemoteAddr());
                request.setAttribute("ip",request.getRemoteAddr());
            }

            log.info("class-method={}", pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());

            Object[] args = pjp.getArgs();
            String contentType = request.getHeader("Content-Type");
            //此处要排除流文件类型,比如上传的文件
            if (args != null && args.length > 0) {
                if(StringUtil.isNullorEmpty(contentType) || (StringUtil.notNullAndWhitSpace(contentType) && !contentType.startsWith("multipart/form-data"))){
                    log.info("----------请求参数----------");
                    log.info("args={}", JSON.toJSONString(args));
                }

            }

        } catch (Exception e) {
            log.error("参数打印错误={}", e.getMessage());
        }

    }

}
